<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\LaborAttendance;
use App\Models\Project;
use Illuminate\Support\Facades\Log;

class LaborAttendanceService
{
    public function get()
    {
        $sql = LaborAttendance::with('labor')->with('project')->with('team');
        return $sql;
    }

    public function laborStatistics($company_id,$labor_id,$team_id,$project_id,$start_date,$end_date)
    {
        $sql = LaborAttendance::where('company_id', $company_id)->where('labor_id', $labor_id)->where('team_id', $team_id)->where('project_id', $project_id);
        if($start_date){
            $sql->whereDate('attendance_date',' >= ',Date('Y-m-d',$start_date / 1000));
        }
        if($end_date){
            $sql->whereDate('attendance_date',' <= ',Date('Y-m-d',$end_date / 1000));
        }

        //总考勤天数
        $data = [];
        $data['total'] = $sql->count();
        //缺勤天数
        $data['absence'] = $sql->count();
        // 迟到
        $data['be_late'] = $sql->whereNull('in_time')->count();
        //早退
        $data['leave_early'] = $sql->whereNull('out_time')->count();
        return $data;
    }

    public function situation($input)
    {
        // 计算距离,
        $project = Project::select('id','map_address','situation','company_id')->where('id',$input['project_id'])->first();
        if($project->situation){
            $distance = $this->getDistanceBetweenTwoPoints($project->situation,$input['situation']);
            if($distance > 30){
                throw new InvalidRequestException('太远了，无法打卡');
            }
        }

        return true;
    }

    public function attendance($input)
    {
        // 计算距离,
        $project = Project::select('id','map_address','situation','company_id')->where('id',$input['project_id'])->first();

        //判断是否打卡过了
        $period = date('a');
        $date = Date("Y-m-d");
        $input['attendance_date'] = $date;
        $is = LaborAttendance::where('labor_id', $input['labor_id'])->where('attendance_date',$date)->where('project_id',$input['project_id'])->where('team_id',$input['team_id'])->first();
        if($is){
            if($period === 'am' && !empty($is->in_time)){
                throw new InvalidRequestException('已经打过卡了');
            }
            if($period === 'pm' && !empty($is->out_time)){
                throw new InvalidRequestException('已经打过卡了');
            }
        }

        if($period === 'am'){
            $input['in_time'] = Date('H:i:s');
        }
        if($period === 'pm'){
            $input['out_time'] = Date('H:i:s');
        }
        $input['work_hours'] = 4.5;
        $res = [];
        foreach ($input as $k => $v) {
            if ($v) {
                $res[$k] = $v;
            }
        }
        $res['company_id'] = $project->company_id;
        try {
            if($is){
                $is->out_time = $input['out_time'];
                $is->work_hours = $input['work_hours'];
                if($is->in_time){
                    $is->work_hours = $this->calculateWorkDuration($is->in_time,$is->out_time);
                }
                $is->save();
                return $is->id;
            }

            $data = LaborAttendance::create($res);
            if ($data) {
                return $data->id;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    function getDistanceBetweenTwoPoints($go, $to,$unit = 'km') {
        $go = explode(',',$go);
        $to = explode(',',$to);
        $lat1Rad = $go[0];
        $lon1Rad = $go[1];
        $lat2Rad = $to[0];
        $lon2Rad = $to[1];
        // WGS84椭球参数（更接近地球实际形状）
        $earthRadius = 6378137; // 赤道半径（米）

        // 计算纬度差和经度差（弧度）
        $deltaLat = $lat2Rad - $lat1Rad;
        $deltaLon = $lon2Rad - $lon1Rad;

        // 计算两点的平均纬度（用于修正经度差）
        $latAvg = ($lat1Rad + $lat2Rad) / 2;

        // 平面近似计算距离（米）
        $distanceMeters = $earthRadius * sqrt(
            pow($deltaLat, 2) +
            pow($deltaLon * cos($latAvg), 2)
        );

        // 转换单位
        switch ($unit) {
            case 'm':
                return round($distanceMeters, 2);
            case 'km':
                return round($distanceMeters / 1000, 2);
            default:
                return round($distanceMeters, 2);
        }
    }

    /**
     * 计算两个时分秒之间的工作时长
     * @param string $startTime 开始时间，格式如 "09:30:00"
     * @param string $endTime 结束时间，格式如 "18:15:00"
     * @return string 时长，格式如 "8小时45分钟" 或 "8.75小时"
     */
    function calculateWorkDuration($startTime, $endTime) {
        // 转换为时间戳（使用任意日期，仅关注时分秒）
        $start = strtotime("2023-01-01 " . $startTime);
        $end = strtotime("2023-01-01 " . $endTime);

        // 处理跨天情况（如夜班）
        if ($end < $start) {
            $end += 86400; // 加上一天的秒数（24*60*60）
        }

        // 计算秒数差
        $seconds = $end - $start;

        // 转换为小时和分钟
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);

        // 可选：返回小数形式的小时
        $totalHours = $seconds / 3600;
        return round($totalHours, 2);
        // return [
        //     'hours' => $hours,
        //     'minutes' => $minutes,
        //     'total_hours' => round($totalHours, 2),
        //     'formatted' => "{$hours}小时{$minutes}分钟"
        // ];
    }
}
